package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
 @Autowired
 private DishFlavorService dishFlavorService;
 @Autowired
 private CategoryService categoryService;
 @Autowired
 private DishService dishService;
 @Autowired
 private RedisTemplate redisTemplate;




 @Override
 public void save1(DishDto dishDto) {
  //保存菜品的基本信息到菜品表dish
  this.save(dishDto);
  //获取菜品ID
  Long dishId = dishDto.getId();
  // 方式一：通过stream流对口味表里面数据绑定菜品id
  List<DishFlavor> flavors = dishDto.getFlavors();
  flavors.stream().forEach(item -> {
   item.setDishId(dishId);
  });
  dishFlavorService.saveBatch(flavors);

  //方式二：
 /* List<DishFlavor> flavors = dishDto.getFlavors();
  flavors = flavors.stream().map((item) -> {
   item.setDishId(dishId);
   return item;
  }).collect(Collectors.toList());
  //保存菜品口味数据到菜品口味表dish_flavor
  dishFlavorService.saveBatch(flavors);*/
 }

 @Override
 public R<Page> page1(Integer page, Integer pageSize, String name) {
  Page<Dish> pageInfo = new Page<>(page, pageSize);
  Page<DishDto> dishDtoPage = new Page<>();
  LambdaQueryWrapper<Dish> dqw = Wrappers.<Dish>lambdaQuery().like(name != null, Dish::getName, name)
   .orderByDesc(Dish::getUpdateTime);
  this.page(pageInfo, dqw);
  //对象拷贝
  BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
  List<Dish> records = pageInfo.getRecords();
  List<DishDto> list = records.stream().map((item) -> {

   DishDto dishDto = new DishDto();
   BeanUtils.copyProperties(item, dishDto);
   Long categoryId = item.getCategoryId();//分类id
   //根据id查询分类对象
   Category category = categoryService.getById(categoryId);

   if (category != null) {
    String categoryName = category.getName();
    dishDto.setCategoryName(categoryName);
   }
   return dishDto;
  }).collect(Collectors.toList());
  dishDtoPage.setRecords(list);
  return R.success(dishDtoPage);
 }

 @Override
 public Page<DishDto> pageByParams(Integer page, Integer pageSize, String name) {
  DishDto dishDto = new DishDto();
  Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
  this.getBaseMapper().pageByParams(dishDtoPage, dishDto);
  return dishDtoPage;
 }


 public DishDto getByIdWithFlavor(Long id) {
  //查询菜品基本信息，从dish表查询
  Dish dish = this.getById(id);

  DishDto dishDto = new DishDto();
  BeanUtils.copyProperties(dish, dishDto);

  //查询当前菜品对应的口味信息，从dish_flavor表查询
  LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
  queryWrapper.eq(DishFlavor::getDishId, dish.getId());
  List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
  dishDto.setFlavors(flavors);

  return dishDto;
 }

 @Override
 @Transactional
 public void updateWithFlavor(DishDto dishDto) {
  //更新dish表基本信息
  this.updateById(dishDto);

  //清理当前菜品对应口味数据---dish_flavor表的delete操作
  LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
  queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());

  dishFlavorService.remove(queryWrapper);

  //添加当前提交过来的口味数据---dish_flavor表的insert操作
  List<DishFlavor> flavors = dishDto.getFlavors();

  flavors = flavors.stream().map((item) -> {
   item.setDishId(dishDto.getId());
   return item;
  }).collect(Collectors.toList());

  dishFlavorService.saveBatch(flavors);
 }

 @Override
 public R<String> delete1(List<Long> ids) {
  for (Long id : ids) {
   Dish dish = this.getById(id);
   if (dish.getStatus() == 0) {
    this.removeById(id);
   } else {
    throw new CustomException("起售状态菜品不能删除");
   }
  }
  return R.success("删除成功");
 }

 @Override
 public R<String> upDateStatus(Integer status, List<Long> ids) {
  LambdaQueryWrapper<Dish> dqw = new LambdaQueryWrapper<>();
  dqw.in(Dish::getId, ids);
  List<Dish> list = this.list(dqw);
  for (Dish dish : list) {
   dish.setStatus(status);
  }
  this.updateBatchById(list);

//  for (Dish dish : list) {
//   switch (dish.getStatus()) {
//    case 0:
//     dish.setStatus(1);
//     this.updateById(dish);
//     break;
//    case 1:
//     dish.setStatus(0);
//     this.updateById(dish);
//     break;
//   }
//  }
  return R.success("批量修改成功");
 }

 @Override
 public R<List<DishDto>> getDish(Dish dish) {
  //创建查询条件
  LambdaQueryWrapper<Dish> dqw = Wrappers.<Dish>lambdaQuery().eq(dish != null, Dish::getCategoryId, dish.getCategoryId())
   .eq(Dish::getStatus,1).orderByAsc(Dish::getSort)
   .orderByDesc(Dish::getUpdateTime);
  //查找符合条件得菜品
  List<Dish> list = this.list(dqw);

  //通过stream流处理list<Dish>
  List<DishDto> dishDtoList = list.stream().map(item -> {
   //创建Dto对象
   DishDto dishDto = new DishDto();
   BeanUtils.copyProperties(item, dishDto);
   //获取分类ID
   Long categoryId = item.getCategoryId();
   //根据id查询分类对象
   Category category = categoryService.getById(categoryId);
   if (category != null) {
    String categoryName = category.getName();
    dishDto.setCategoryName(categoryName);
   }
   //当前菜品的id
   Long dishId = item.getId();
   LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = Wrappers.<DishFlavor>lambdaQuery()
    .eq(DishFlavor::getDishId, dishId);
   //SQL:select * from dish_flavor where dish_id = ?
   List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
   dishDto.setFlavors(dishFlavorList);
   return dishDto;

  }).collect(Collectors.toList());

   return R.success(dishDtoList);
 }


/* public R<List<Dish>> getDish(Dish dish) {
  LambdaQueryWrapper<Dish> dqw = new LambdaQueryWrapper<>();
  dqw.eq(dish != null, Dish::getCategoryId, dish.getCategoryId())
   .orderByDesc(Dish::getUpdateTime);
  List<Dish> dishes = this.list(dqw);
  return R.success(dishes);
 }*/
}
